package com.waimai1.waimai.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.waimai1.waimai.common.BaseContext;
import com.waimai1.waimai.common.JWTUtil;
import com.waimai1.waimai.common.R;
import com.waimai1.waimai.dto.ChoujiangResDto;
import com.waimai1.waimai.dto.GetLocalGoodDto;
import com.waimai1.waimai.dto.GetOrderListDto;
import com.waimai1.waimai.dto.SaveAndDeletePageContentDto;
import com.waimai1.waimai.entity.*;
import com.waimai1.waimai.exception.EnumException;
import com.waimai1.waimai.exception.NotErrorException;
import com.waimai1.waimai.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/manage")
//@ResponseBody
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private JWTUtil jwtUtil;
    @Autowired
    private LocalShopService localShopService;
    @Autowired
    private LocalGoodService localGoodService;
    @Autowired
    private BannerService bannerService;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private ChoujiangService choujiangService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private TanchuangService tanchuangService;
    @Autowired
    private CouponPersonService couponPersonService;
    @Autowired
    private PinpaiService pinpaiService;
    @Autowired
    private UserService userService;
    @Autowired
    private MyOrderService orderService;
    @Autowired
    private CommissionService commissionService;
    @Autowired
    private DesignComponentService designComponentService;
    @Autowired
    private PageComponentService pageComponentService;
    @Autowired
    private AcidService acidService;
    @Autowired
    private PageInfoService pageInfoService;
    @Autowired
    private ChoujiangResService choujiangResService;

    //获取白名单数量
    @PostMapping("/getredisWhite")
    public R<Long> getredisWhite(@RequestBody Map<String, String> map) {
        return R.success(couponService.getRedisWhite(map.get("id")));
    }

    @PostMapping("/judgeInWhite")
    public R<Boolean> judgeInWhite(@RequestBody Map<String, String> map) {
        return R.success(couponService.hasMember(map.get("key"), map.get("phone")));
    }

    //    下载couponperson数据
    @GetMapping("/downloadPerson/{weino}")
    public void download(@PathVariable String weino, HttpServletResponse response) throws IOException {
        LambdaQueryWrapper<CouponPerson> couponPersonLambdaQueryWrapper = new LambdaQueryWrapper<>();
        couponPersonLambdaQueryWrapper.eq(CouponPerson::getWexinNo, weino);
        couponPersonLambdaQueryWrapper.eq(CouponPerson::getAcid, BaseContext.getAcid());
        List<CouponPerson> persons = couponPersonService.list(couponPersonLambdaQueryWrapper);
        // 改成你想要的文件名
        String fileName = weino + "领取人.xls";
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), CouponPerson.class).build();
        // 调用上一步构建数据的方法
        excelWriter.write(persons, EasyExcel.writerSheet("sheet1").build());
        excelWriter.finish();
    }

    @PostMapping("/login")
    public R<Map<String, Object>> login(@RequestBody Admin admin) {
        if (null == admin.getName() || null == admin.getPassword()) {
            throw new NotErrorException(EnumException.NO_LOGIN);
        }
        admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes(StandardCharsets.UTF_8)));
        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
        adminLambdaQueryWrapper.eq(Admin::getName, admin.getName())
                .eq(Admin::getPassword, admin.getPassword());
        Admin adminRes = adminService.getOne(adminLambdaQueryWrapper);
        if (null == adminRes) {
            throw new NotErrorException(EnumException.NO_LOGIN);
        }
        String token = jwtUtil.createToken(adminRes);
        Map<String, Object> res = new HashMap<>();
        res.put("token", token);
        adminRes.setPassword("");
        res.put("userInfo", adminRes);
        return R.success(res);
    }

    //    @RequestMapping(value={"/notice/{pageId}"},method=RequestMethod.GET)
//    public R<Map<String,Object>> getNotice(@PathVariable Integer pageId){
//        Page<Notice> page=new Page<>(pageId,10);
//        IPage<Notice> noticePage=noticeService.page(page);
//        List<Notice> noticeList=noticePage.getRecords();
//        Long total=noticePage.getTotal();
//        Map<String,Object> res=new HashMap<>();
//        res.put("noticeList",noticeList);
//        res.put("total",total);
//        return R.success(res);
//    };
//    @RequestMapping(value={"/editNotice"},method=RequestMethod.POST)
//    public R<String> editNotice(@RequestBody Notice notice){
//        boolean res=noticeService.saveOrUpdate(notice);
//        if(!res){
//            throw new NotErrorException(EnumException.NO_UPDATE);
//        }
//        return R.success("ok");
//    }
//    @PostMapping("/delNotice")
//    public R<String> delNotice(@RequestBody Notice notice){
//        boolean res=noticeService.removeById(notice.getId());
//        if(!res){
//            throw new NotErrorException(EnumException.NO_DELETE);
//        }
//        return R.success("ok");
//    };
    @RequestMapping(value={"/tanchuang/{pageId}"},method=RequestMethod.GET)
    public R<Map<String,Object>> getTanchuang(@PathVariable Integer pageId){
        Page<Tanchuang> page=new Page<>(pageId,10);
        IPage<Tanchuang> tanchuangPage=tanchuangService.page(page);
        List<Tanchuang> tanchuangList=tanchuangPage.getRecords();
        Long total=tanchuangPage.getTotal();
        Map<String,Object> res=new HashMap<>();
        res.put("tanchuangList",tanchuangList);
        res.put("total",total);
        return R.success(res);
    };
    @RequestMapping(value={"/editTanchuang"},method=RequestMethod.POST)
    public R<String> editTanchuang(@RequestBody Tanchuang tanchuang){
        boolean res=tanchuangService.saveOrUpdate(tanchuang);
        if(!res){
            throw new NotErrorException(EnumException.NO_UPDATE);
        }
        return R.success("ok");
    }
//    @RequestMapping(value={"/banner/{pageId}"},method=RequestMethod.GET)
//    public R<Map<String,Object>> getBanner(@PathVariable Integer pageId){
//        Page<Banner> page=new Page<>(pageId,10);
//        IPage<Banner> bannerPage=bannerService.page(page);
//        List<Banner> bannerList=bannerPage.getRecords();
//        Long total=bannerPage.getTotal();
//        Map<String,Object> res=new HashMap<>();
//        res.put("bannerList",bannerList);
//        res.put("total",total);
//        return R.success(res);
//    };
//
//    @RequestMapping(value={"/editBanner"},method=RequestMethod.POST)
//    public R<String> editBanner(@RequestBody Banner banner){
//        boolean res=bannerService.saveOrUpdate(banner);
//        if(!res){
//            throw new NotErrorException(EnumException.NO_UPDATE);
//        }
//        return R.success("ok");
//    }
//    @PostMapping("/delBanner")
//    public R<String> delBanner(@RequestBody Banner banner){
//        boolean res=bannerService.removeById(banner.getId());
//        if(!res){
//            throw new NotErrorException(EnumException.NO_DELETE);
//        }
//        return R.success("ok");
//    };
    @PostMapping("/delChoujiang")
    public R<String> delChoujiang(@RequestBody Choujiang choujiang) {
        boolean res = choujiangService.removeById(choujiang.getId());
        if (!res) {
            throw new NotErrorException(EnumException.NO_DELETE);
        }
        return R.success("ok");
    }

    ;

    @RequestMapping(value = {"/savechoujiang"}, method = RequestMethod.POST)
    public R<String> savechoujiang(@RequestBody Choujiang choujiang) {
        choujiang.setAcid(BaseContext.getAcid());
        boolean res = choujiangService.saveOrUpdate(choujiang);
        if (!res) {
            throw new NotErrorException(EnumException.NO_UPDATE);
        }
        return R.success("ok");
    }

    @GetMapping("/getChoujiang/{pageIndex}")
    public R<Map<String, Object>> getChoujiang(@PathVariable Integer pageIndex) {
        LambdaQueryWrapper<Choujiang> choujiangLambdaQueryWrapper = new LambdaQueryWrapper<>();
        choujiangLambdaQueryWrapper.eq(Choujiang::getAcid, BaseContext.getAcid());
        Page<Choujiang> page = new Page<>(pageIndex, 10);
        IPage<Choujiang> choujiangPage = choujiangService.page(page, choujiangLambdaQueryWrapper);
        List<Choujiang> choujiangList = choujiangPage.getRecords();
        Long total = choujiangPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("choujiangList", choujiangList);
        res.put("total", total);
        return R.success(res);
    }

    @RequestMapping(value = {"/coupon"}, method = RequestMethod.POST)
    public R<Map<String, Object>> coupon(@RequestBody Map<String, Object> params) {
        String wexinNo = (String) params.get("wexinNo");
        String name = (String) params.get("name");
        String status = (String) params.get("status");
        Integer pageId = (Integer) params.get("pageIndex");
        LambdaQueryWrapper<Coupon> couponLambdaQueryWrapper = new LambdaQueryWrapper<>();
        couponLambdaQueryWrapper.eq(Coupon::getAcid, BaseContext.getAcid())
                .eq(StringUtils.isNotBlank(wexinNo), Coupon::getWexinNo, wexinNo)
                .eq(StringUtils.isNotBlank(status), Coupon::getStatus, status)
                .like(StringUtils.isNotBlank(name), Coupon::getName, name);
        Page<Coupon> page = new Page<>(pageId, 10);
        IPage<Coupon> couponPage = couponService.page(page, couponLambdaQueryWrapper);
        List<Coupon> couponList = couponPage.getRecords();
        Long total = couponPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("couponList", couponList);
        res.put("total", total);
        return R.success(res);
    }

    ;

    @RequestMapping(value = {"/editCoupon"}, method = RequestMethod.POST)
    public R<String> editCoupon(@RequestBody Coupon coupon) {
        coupon.setAcid(BaseContext.getAcid());
        boolean res = couponService.saveOrUpdate(coupon);
        if (!res) {
            throw new NotErrorException(EnumException.NO_UPDATE);
        }
        return R.success("ok");
    }

    ;

    @RequestMapping(value = "/coupon/{id}", method = RequestMethod.DELETE)
    public R<String> deleteCoupon(@PathVariable int id) {
        if (!couponService.removeById(id)) {
            throw new NotErrorException(EnumException.NO_DELETE);
        }
        ;
        return R.success("ok");
    }

    @RequestMapping(value = "/couponPerson/{id}", method = RequestMethod.DELETE)
    public R<String> deleteCouponPerson(@PathVariable int id) {
        if (!couponPersonService.removeById(id)) {
            throw new NotErrorException(EnumException.NO_DELETE);
        }
        ;
        return R.success("ok");
    }

    //按输入框创建白名单
    @RequestMapping(value = {"/createCouponPerson"}, method = RequestMethod.POST)
    public R<Long> createCouponPerson(@RequestBody CouponPerson couponPerson) {
//        处理带逗号的phone
        BaseContext.setWexinNo(couponPerson.getWexinNo());
        String[] phonelist = couponPerson.getPhone().split("-");
        long s = couponPersonService.saveWhite(phonelist);
        return R.success(s);
        //不再使用数据库，改用redis
//        if(phonelist.length==0){
//            throw new NotErrorException(EnumException.NO_SAVE);
//        }
//        ArrayList<CouponPerson> couponPersonArrayList=new ArrayList<>();
//        for(String phone : phonelist){
//            CouponPerson tempPerson=new CouponPerson();
//            tempPerson.setCouponId(couponPerson.getCouponId());
//            tempPerson.setPhone(phone);
//            tempPerson.setCreateTime(new Date());
//            tempPerson.setStatus("未领取");
//            couponPersonArrayList.add(tempPerson);
//        }
//        boolean res=couponPersonService.saveBatch(couponPersonArrayList);
//        if(!res){
//            throw new NotErrorException(EnumException.NO_SAVE);
//        }
        //券发放数量更新到coupen表
//        LambdaQueryWrapper<Coupon> queryWrapper =new LambdaQueryWrapper<>();
//        queryWrapper.eq(Coupon::getWexinNo,couponPerson.getCouponId());
//        Coupon tempCoupon=couponService.getOne(queryWrapper);
//        if(null!=tempCoupon){
//            tempCoupon.setSendCoupnt(tempCoupon.getSendCount()+phonelist.length);
//            couponService.updateById(tempCoupon);
//        }
//        return R.success("ok");
    }

    //获取领券人列表
    @RequestMapping(value = {"/couponPerson"}, method = RequestMethod.POST)
    public R<Map<String, Object>> couponPerson(@RequestBody Map<String, Object> params) {
        String wexinNo = (String) params.get("wexinNo");
        String status = (String) params.get("status");
        String phone = (String) params.get("phone");
        Integer pageId = (Integer) params.get("pageIndex");
        LambdaQueryWrapper<CouponPerson> couponPersonLambdaQueryWrapper = new LambdaQueryWrapper<>();
        couponPersonLambdaQueryWrapper.eq(StringUtils.isNotBlank(wexinNo), CouponPerson::getWexinNo, wexinNo)
                .eq(CouponPerson::getAcid, BaseContext.getAcid())
                .eq(StringUtils.isNotBlank(status), CouponPerson::getStatus, status)
                .eq(StringUtils.isNotBlank(phone), CouponPerson::getPhone, phone);
        Page<CouponPerson> page = new Page<>(pageId, 10);
        IPage<CouponPerson> couponPage = couponPersonService.page(page, couponPersonLambdaQueryWrapper);
        List<CouponPerson> couponPersonList = couponPage.getRecords();
        Long total = couponPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("couponPersonList", couponPersonList);
        res.put("total", total);
        return R.success(res);
    }

    @RequestMapping(value = {"/pinpai/{pageId}"}, method = RequestMethod.GET)
    public R<Map<String, Object>> pinpai(@PathVariable Integer pageId) {
        Page<Pinpai> page = new Page<>(pageId, 20);
        IPage<Pinpai> pinpaiPage = pinpaiService.page(page);
        List<Pinpai> pinpaiList = pinpaiPage.getRecords();
        Long total = pinpaiPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("pinpaiList", pinpaiList);
        res.put("total", total);
        return R.success(res);
    }

    ;

    @PostMapping("/editPinpai")
    public R<String> editPinpai(@RequestBody Pinpai pinpai) {
        boolean res = pinpaiService.saveOrUpdate(pinpai);
        if (!res) {
            throw new NotErrorException(EnumException.NO_UPDATE);
        }
        return R.success("ok");
    }

    ;

    @PostMapping("/getSearchShop")
    public R<Map<String, Object>> getSearchShop(@RequestBody Map<String, Object> map) {
        LambdaQueryWrapper<LocalShop> queryWrapper = new LambdaQueryWrapper<>();
        String search = (String) map.get("search");
        String sort = (String) map.get("sort");
        String status = (String) map.get("status");
        queryWrapper.eq(StringUtils.isNotEmpty(sort), LocalShop::getSort, sort)
                .eq(StringUtils.isNotEmpty(status), LocalShop::getStatus, status)
                .eq(LocalShop::getAcid,BaseContext.getAcid())
                .like(StringUtils.isNotEmpty(search), LocalShop::getShopName, search)
                .orderByAsc(LocalShop::getNo);
        Page<LocalShop> page = new Page<>((Integer) map.get("page"), 10);
        IPage<LocalShop> shopPage = localShopService.page(page, queryWrapper);
        List<LocalShop> shopList = shopPage.getRecords();
        Long total = shopPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("shopList", shopList);
        res.put("total", total);
        return R.success(res);
    }

    @PostMapping("/editShop")
    public R<String> editShop(@RequestBody LocalShop shop) {
        shop.setAcid(BaseContext.getAcid());
        boolean res = localShopService.saveOrUpdate(shop);
        if (!res) {
            throw new NotErrorException(EnumException.NO_UPDATE);
        }
        return R.success("ok");
    }

    @PostMapping("/delShop")
    public R<String> delShop(@RequestBody LocalShop localShop) {
        boolean res = localShopService.removeById(localShop);
        if (!res) {
            throw new NotErrorException(EnumException.NO_DELETE);
        }
        return R.success("ok");
    }

    @PostMapping("/getGood")
    public R<Map<String, Object>> getSearchGood(@RequestBody GetLocalGoodDto localGoodDto) {
        Date startTime = null, endTime = null;
        if (null != localGoodDto.getSelectTime()) {
            startTime = localGoodDto.getSelectTime()[0];
            endTime = localGoodDto.getSelectTime()[1];
        }
        LambdaQueryWrapper<LocalGood> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != localGoodDto.getShopId(), LocalGood::getShopId, localGoodDto.getShopId())
                .eq(LocalGood::getAcid,BaseContext.getAcid())
                .like(StringUtils.isNotEmpty(localGoodDto.getGoodName()), LocalGood::getGoodName, localGoodDto.getGoodName())
                .between(null != localGoodDto.getSelectTime(), LocalGood::getCreateTime, startTime, endTime)
                .orderByDesc(LocalGood::getCreateTime);
        Page<LocalGood> page = new Page<>(localGoodDto.getPageIndex(), 10);
        IPage<LocalGood> goodPage = localGoodService.page(page, queryWrapper);
        List<LocalGood> goodList = goodPage.getRecords();
        Long total = goodPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("goodList", goodList);
        res.put("total", total);
        return R.success(res);
    }

    @RequestMapping(value = {"/user"}, method = RequestMethod.POST)
    public R<Map<String, Object>> user(@RequestBody Map<String, Object> params) {
        String name = (String) params.get("name");
        String openid = (String) params.get("openid");
        String phone = (String) params.get("phone");
        String status = (String) params.get("status");
        Integer pageId = (Integer) params.get("pageIndex");
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(StringUtils.isNotBlank(status), User::getStatus, status)
                .eq(User::getAcid,BaseContext.getAcid())
                .eq(StringUtils.isNotBlank(phone), User::getPhone, phone)
                .eq(StringUtils.isNotBlank(openid), User::getOpenid, openid)
                .like(StringUtils.isNotBlank(name), User::getName, name);
        Page<User> page = new Page<>(pageId, 10);
        IPage<User> userPage = userService.page(page, userLambdaQueryWrapper);
        List<User> userList = userPage.getRecords();
        Long total = userPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("userList", userList);
        res.put("total", total);
        return R.success(res);
    }
    @RequestMapping(value={"/editGood"},method=RequestMethod.POST)
    public R<String> editGood(@RequestBody LocalGood localGood){
        boolean res=localGoodService.saveOrUpdate(localGood);
        if(!res){
            throw new NotErrorException(EnumException.NO_UPDATE);
        }
        return R.success("ok");
    }
    @RequestMapping(value="/good/{id}",method=RequestMethod.DELETE)
    public R<String> deleteGoodList(@PathVariable int id){
        if(!localGoodService.removeById(id)){
            throw new NotErrorException(EnumException.NO_DELETE);
        };
        return R.success("ok");
    }
    @RequestMapping(value = {"/editUser"}, method = RequestMethod.POST)
    public R<String> editUser(@RequestBody User user) {
        user.setAcid(BaseContext.getAcid());
        boolean res = userService.saveOrUpdate(user);
        if (!res) {
            throw new NotErrorException(EnumException.NO_UPDATE);
        }
        return R.success("ok");
    }

    @RequestMapping(value = "/user/{id}", method = RequestMethod.DELETE)
    public R<String> deleteUserList(@PathVariable int id) {
        if (!userService.removeById(id)) {
            throw new NotErrorException(EnumException.NO_DELETE);
        }
        ;
        return R.success("ok");
    }

    //    下载couponperson数据
    @GetMapping("/downloadUser")
    public void downloadUser(HttpServletResponse response) throws IOException {
        List<User> persons = userService.list();
        // 改成你想要的文件名
        String fileName = "user.xls";
        response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), User.class).build();
        // 调用上一步构建数据的方法
        excelWriter.write(persons, EasyExcel.writerSheet("sheet1").build());
        excelWriter.finish();
    }

    @RequestMapping(value = {"/getOrderList"}, method = RequestMethod.POST)
    public R<Map<String, Object>> getOrderList(@RequestBody GetOrderListDto getOrderListDto) {
        Date startTime = null, endTime = null;
        if (null != getOrderListDto.getSelectTime()) {
            startTime = getOrderListDto.getSelectTime()[0];
            endTime = getOrderListDto.getSelectTime()[1];
        }
        LambdaQueryWrapper<MyOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(null != getOrderListDto.getMovieName(), MyOrder::getMovieName, getOrderListDto.getMovieName())
                .eq(MyOrder::getAcid,BaseContext.getAcid())
                .eq(null != getOrderListDto.getOpenid(), MyOrder::getOpenid, getOrderListDto.getOpenid())
                .eq(null != getOrderListDto.getTakePhone(), MyOrder::getTakePhone, getOrderListDto.getTakePhone())
                .eq(null != getOrderListDto.getStatus(), MyOrder::getStatus, getOrderListDto.getStatus())
                .between(null != getOrderListDto.getSelectTime(), MyOrder::getCreateTime, startTime, endTime)
                .like(null != getOrderListDto.getOutTradeNo(), MyOrder::getOutTradeNo, getOrderListDto.getOutTradeNo());
//判断是电影订单还是品牌订单
        if ("movie".equals(getOrderListDto.getMovieOrpp())) {
            wrapper.isNotNull(MyOrder::getHallName);
        } else if ("pp".equals(getOrderListDto.getMovieOrpp())) {
            wrapper.isNotNull(MyOrder::getEatType);
        } else if ("ls".equals(getOrderListDto.getMovieOrpp())) {
            wrapper.isNull(MyOrder::getSeat);
        }
        wrapper.orderByDesc(MyOrder::getUpdateTime);
        Page<MyOrder> page = new Page<>(getOrderListDto.getPageIndex(), 10);
        IPage<MyOrder> orderPage = orderService.page(page, wrapper);
        List<MyOrder> orderList = orderPage.getRecords();
        Long total = page.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("orderList", orderList);
        res.put("total", total);
        return R.success(res);
    }
//品牌是否上架
    @PostMapping("/PPswitch")
    public R<String> PPswitch(@RequestBody Pinpai pinpai) {
        if (!pinpaiService.updateById(pinpai)) {
            throw new NotErrorException(EnumException.NO_SWITCH_PP);
        }
        return R.success("");
    }

    @RequestMapping(value = "/admin/{pageId}", method = RequestMethod.GET)
    public R<Map<String, Object>> getAdminList(@PathVariable Integer pageId) {
        Page<Admin> page = new Page<>(pageId, 10);
        IPage<Admin> adminPage = adminService.page(page);
        List<Admin> adminList = adminPage.getRecords();
        Long total = adminPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("adminList", adminList);
        res.put("total", total);
        return R.success(res);
    }

    @RequestMapping(value = "/admin/{id}", method = RequestMethod.DELETE)
    public R<String> deleteAdminList(@PathVariable int id) {
        if (!adminService.removeById(id)) {
            throw new NotErrorException(EnumException.NO_DELETE);
        }
        ;
        return R.success("ok");
    }

    @PostMapping(value = "/changeAdmin")
    public R<String> changeAdmin(@RequestBody Map<String, String> map) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        String name = BaseContext.getName();
        System.out.println(name);
        queryWrapper.eq(Admin::getName, name);
        Admin admin = adminService.getOne(queryWrapper);
        if (DigestUtils.md5DigestAsHex(map.get("old").getBytes(StandardCharsets.UTF_8)).equals(admin.getPassword())) {
            admin.setPassword(DigestUtils.md5DigestAsHex(map.get("new").getBytes(StandardCharsets.UTF_8)));
            if (!adminService.update(admin, queryWrapper)) {
                throw new NotErrorException(EnumException.NO_UPDATE);
            }
            ;
        }
        return R.success("ok");
    }

    @RequestMapping(value = {"/commission"}, method = RequestMethod.GET)
    public R<List<Commission>> getCommission() {
        List<Commission> res = commissionService.list();
        return R.success(res);
    }

    ;

    @RequestMapping(value = {"/commission"}, method = RequestMethod.POST)
    public R<String> changeCommission(@RequestBody List<Commission> commissions) {
        boolean res = commissionService.updateBatchById(commissions);
        if (!res) {
            throw new NotErrorException(EnumException.NO_UPDATE);
        }
        return R.success("ok");
    }

    ;

    @PostMapping("/shopLogin")
    public R<Map<String, Object>> shopLogin(@RequestBody LocalShop localShop) {
        if (null == localShop.getPhone() || null == localShop.getPass()) {
            throw new NotErrorException(EnumException.NO_LOGIN);
        }
        localShop.setPass(DigestUtils.md5DigestAsHex(localShop.getPass().getBytes(StandardCharsets.UTF_8)));
        LambdaQueryWrapper<LocalShop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LocalShop::getPhone, localShop.getPhone())
                .eq(LocalShop::getPass, localShop.getPass());
        LocalShop one = localShopService.getOne(queryWrapper);
        if (null == one) {
            throw new NotErrorException(EnumException.NO_LOGIN);
        }
        String token = jwtUtil.createToken(one);
        Map<String, Object> res = new HashMap<>();
        res.put("token", token);
        one.setPass("");
        res.put("localshopInfo", one);
        return R.success(res);
    }

    /**
     * 获取设计页面元素
     *
     * @return 元素列表
     */
    @GetMapping("getDesignComponent")
    public R<List<DesignComponent>> getDesignComponent() {
        List<DesignComponent> designComponents = designComponentService.list();
        return R.success(designComponents);
    }

    /**
     * 获取页面
     *
     * @return 元素列表
     */
    @GetMapping("getPage")
    public R<List<PageInfo>> getPage() {
        LambdaQueryWrapper<PageInfo> pageInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
        pageInfoLambdaQueryWrapper.eq(PageInfo::getAcid,BaseContext.getAcid());
        List<PageInfo> pages = pageInfoService.list(pageInfoLambdaQueryWrapper);
        return R.success(pages);
    }
    @PostMapping("getPageByName")
    public R<PageInfo> getPageByName(@RequestBody String name) {
        log.info(BaseContext.getAcid().toString());
        LambdaQueryWrapper<PageInfo> pageInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
        pageInfoLambdaQueryWrapper.eq(PageInfo::getAcid,BaseContext.getAcid())
        .eq(PageInfo::getName,name);
        PageInfo page = pageInfoService.getOne(pageInfoLambdaQueryWrapper,false);
        return R.success(page);
    }
    //    保存组件信息
    @PostMapping("savePageContent")
    public R<String> savePageContent(@RequestBody SaveAndDeletePageContentDto dto) {
        for(PageComponent pageComponent : dto.getPageComponentList()){
            pageComponent.setAcid(BaseContext.getAcid());
        }
        pageComponentService.saveOrUpdateBatch(dto.getPageComponentList());
        pageComponentService.removeByIds(dto.getDeletedComponentIdList());
        return R.success("ok");
    }
    //    创建新页面
    @PostMapping("createPage")
    public R<String> createPage(@RequestBody PageInfo pageInfo) {
        pageInfo.setAcid(BaseContext.getAcid());
        if (!pageInfoService.saveOrUpdate(pageInfo)) {
            throw new NotErrorException(1007, "保存页面失败");
        }
        return R.success("ok");
    }

    //删除页面
    @PostMapping("delPage")
    public R<String> delPage(@RequestBody PageInfo pageInfo) {
        if (!pageInfoService.removeById(pageInfo.getId())) {
            throw new NotErrorException(1007, "删除页面失败");
        }
        return R.success("ok");
    }

    //获取acidList
    @GetMapping("getAcidList")
    public R<List<Acid>> getAcidList() {
        return R.success(acidService.list());
    }
    @PostMapping("editAcid")
    public R<String> editAcid(@RequestBody Acid acid){
//        判断是否是新建
        boolean newFlag=false;
        if(null==acid.getId()){
            newFlag=true;
        }
        if(!acidService.saveOrUpdate(acid)){
            throw new NotErrorException(EnumException.NO_UPDATE);
        }
        // 如果为新建则创建index和my页面
        if(newFlag){
            LambdaQueryWrapper<Acid> acidLambdaQueryWrapper=new LambdaQueryWrapper<>();
            acidLambdaQueryWrapper.eq(Acid::getName,acid.getName());
            acid=acidService.getOne(acidLambdaQueryWrapper);
            PageInfo pageInfo=new PageInfo();
            pageInfo.setName("首页");
            pageInfo.setAcid(acid.getId());
            pageInfoService.save(pageInfo);
            LambdaQueryWrapper<PageInfo> pageInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
            pageInfoLambdaQueryWrapper.eq(PageInfo::getAcid,acid.getId())
                    .eq(PageInfo::getName,"首页");
            pageInfo=pageInfoService.getOne(pageInfoLambdaQueryWrapper);
            pageInfo.setLink("../1index/index?acid="+pageInfo.getAcid()+"&h="+pageInfo.getId());
            pageInfoService.updateById(pageInfo);
            PageInfo myPageInfo=new PageInfo();
            myPageInfo.setName("我的");
            myPageInfo.setAcid(acid.getId());
            pageInfoService.save(myPageInfo);
            pageInfoLambdaQueryWrapper=new LambdaQueryWrapper<>();
            pageInfoLambdaQueryWrapper.eq(PageInfo::getAcid,acid.getId())
                    .eq(PageInfo::getName,"我的");
            myPageInfo=pageInfoService.getOne(pageInfoLambdaQueryWrapper);
            myPageInfo.setLink("../4my/my?h="+myPageInfo.getId());
            pageInfoService.updateById(myPageInfo);
        }
        return R.success("ok");
    }
    @RequestMapping(value = "/acid/{id}", method = RequestMethod.DELETE)
    public R<String> deleteAcid(@PathVariable int id) {
        if (!acidService.removeById(id)) {
            throw new NotErrorException(EnumException.NO_DELETE);
        }
        return R.success("ok");
    }
//    获取抽奖记录
    @PostMapping("/getChoujiangResList")
    public R<Map<String, Object>> getChoujiangResList(@RequestBody ChoujiangResDto choujiangResDto) {
        LambdaQueryWrapper<ChoujiangRes> choujiangResLambdaQueryWrapper=new LambdaQueryWrapper<>();
        choujiangResLambdaQueryWrapper
                .eq(ChoujiangRes::getAcid,BaseContext.getAcid())
                .eq(null!=choujiangResDto.getChoujiangId(),ChoujiangRes::getChoujiangId,choujiangResDto.getChoujiangId())
                .eq(StringUtils.isNotBlank(choujiangResDto.getPhone()),ChoujiangRes::getPhone,choujiangResDto.getPhone())
                .eq(StringUtils.isNotBlank(choujiangResDto.getJiangName()),ChoujiangRes::getJiangName,choujiangResDto.getJiangName());

        Page<ChoujiangRes> page = new Page<>(choujiangResDto.getPageIndex(), choujiangResDto.getPageSize());
        IPage<ChoujiangRes> choujiangResPage = choujiangResService.page(page,choujiangResLambdaQueryWrapper);
        List<ChoujiangRes> choujiangResList = choujiangResPage.getRecords();
        Long total = choujiangResPage.getTotal();
        Map<String, Object> res = new HashMap<>();
        res.put("choujiangResList", choujiangResList);
        res.put("total", total);
        return R.success(res);
    }
}
